import 'dart:async';
import 'dart:io';

class NettyClient {
  static const String SERVER_HOST = '119.3.198.149';
  static const int SERVER_PORT = 8082;
  static const int READ_IDLE_TIME = 10; // 读空闲时间（秒）
  static const int WRITE_IDLE_TIME = 5; // 写空闲时间（秒）
  static const int ALL_IDLE_TIME = 15; // 读写空闲时间（秒）
  static const int RECONNECT_DELAY = 5; // 重连延迟时间（秒）

  Socket? _socket;
  Timer? _heartbeatTimer;
  Timer? _reconnectTimer;

  // 连接到服务器
  Future<void> connect() async {
    try {
      _socket = await Socket.connect(SERVER_HOST, SERVER_PORT);
      print('Connected to server');
      _startHeartbeat();
      _listenForMessages();
    } catch (e) {
      print('Connection error: $e');
      _reconnect();
    }
  }

  // 发送消息
  void sendMessage(String message) {
    if (_socket != null) {
      _socket!.write('$message\n');
    } else {
      print('Socket is not connected, cannot send message');
    }
  }

  // 启动心跳机制
  void _startHeartbeat() {
    _heartbeatTimer = Timer.periodic(Duration(seconds: WRITE_IDLE_TIME), (timer) {
      sendMessage('Heartbeat');
      print('Sent heartbeat');
    });
  }

  // 停止心跳机制
  void _stopHeartbeat() {
    _heartbeatTimer?.cancel();
  }

  // 监听服务器消息
  void _listenForMessages() {
    _socket?.listen((List<int> data) {
      String message = String.fromCharCodes(data).trim();
      print('Received message: $message');
    }, onError: (error) {
      print('Error receiving message: $error');
      _socket?.destroy();
      _reconnect();
    }, onDone: () {
      print('Connection closed by server');
      _reconnect();
    });
  }

  // 重连
  void _reconnect() {
    _stopHeartbeat();
    _reconnectTimer = Timer(Duration(seconds: RECONNECT_DELAY), () {
      print('Trying to reconnect...');
      connect();
    });
  }

  // 断开连接
  void disconnect() {
    _stopHeartbeat();
    _reconnectTimer?.cancel();
    _socket?.destroy();
  }
}